import json
import functools
import os

from tasks.constants import TASK_STATUS_FILE

class StatusManager:
    def __init__(self, json_file_path):
        self.json_file_path = json_file_path
        self.status_dict = self.load_tool_status()

    def load_tool_status(self):
        """
        加载JSON文件中的工具执行状态
        """
        if os.path.isfile(self.json_file_path):
            with open(self.json_file_path, 'r') as file:
                return json.load(file) or {}
        else:
            return {}

    def save_tool_status(self, tool_name, status):
        """
        更新并保存工具在JSON文件中的执行状态
        """
        self.status_dict[tool_name] = status
        with open(self.json_file_path, 'w') as file:
            json.dump(self.status_dict, file, indent=4)

    def skip_if_success_decorator(self, func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            tool_name = func.__name__  # 假设函数名即为工具名
            if tool_name not in self.status_dict or self.status_dict[tool_name] != 'success':
                try:
                    result = func(*args, **kwargs)
                    if result:
                        self.save_tool_status(tool_name, 'success')
                    else:
                        self.save_tool_status(tool_name, 'failed')
                    return result
                except Exception as e:
                    self.save_tool_status(tool_name, 'failed')
                    raise e
            else:
                print(f"{tool_name} has already been executed successfully, skipping...")
        return wrapper

status_manager = StatusManager(TASK_STATUS_FILE)

if __name__ == '__main__':
    # 示例使用
    # status_manager = StatusManager('tool_execution_status.json')

    @status_manager.skip_if_success_decorator
    def example_tool_execution():
        print("Executing example tool...")

    # 调用工具执行函数
    example_tool_execution()